#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
初始化角色和权限数据脚本
用于创建初始角色、权限并为用户分配角色
"""

import sys
import os

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app import create_app
from app.models.user import User
from app.models.role import Role, Permission
from app.models.init_roles import init_roles_and_permissions, assign_admin_role
from app.extensions import db

def init_all():
    """初始化所有数据"""
    app = create_app()
    
    with app.app_context():
        # 初始化角色和权限
        init_roles_and_permissions()
        
        # 为管理员用户分配管理员角色
        admin_user = User.query.filter_by(username='admin').first()
        if admin_user:
            assign_admin_role(admin_user)
        
        # 为普通用户分配普通角色
        user1 = User.query.filter_by(username='user1').first()
        if user1:
            viewer_role = Role.query.filter_by(name='viewer').first()
            if viewer_role and not user1.has_role('viewer'):
                user1.add_role(viewer_role)
                db.session.commit()
                print(f"已为用户 {user1.username} 分配查看者角色")
        
        user2 = User.query.filter_by(username='user2').first()
        if user2:
            author_role = Role.query.filter_by(name='author').first()
            if author_role and not user2.has_role('author'):
                user2.add_role(author_role)
                db.session.commit()
                print(f"已为用户 {user2.username} 分配作者角色")
        
        print("角色和权限分配完成!")

if __name__ == '__main__':
    init_all()